package com.rzjm.exercise.common.exception;

import com.rzjm.exercise.common.constant.Constant;
import com.rzjm.exercise.common.utils.HttpServletUtils;
import com.rzjm.exercise.common.utils.R;
import com.rzjm.exercise.common.utils.ShiroUtils;
import com.rzjm.exercise.sys.core.log.domain.LogDO;
import com.rzjm.exercise.sys.core.log.service.LogService;
import com.rzjm.exercise.sys.system.user.domain.UserDO;

import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import java.util.Date;

/**
 * 异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    LogService logService;

    @ExceptionHandler(AuthorizationException.class)
    public Object handleAuthorizationException(AuthorizationException e, HttpServletRequest request) {
        logger.error(e.getMessage(), e);
        if (HttpServletUtils.jsAjax(request)) {
            return R.error(403, "未授权");
        }
        return new ModelAndView("error/403");
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public R handle(ConstraintViolationException exception) {
        StringBuilder builder = new StringBuilder();
        for (ConstraintViolation<?> item : exception.getConstraintViolations()) {
            builder.append("," + item.getMessage());
        }

        return R.error(builder.toString().replace(",", ""));
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public R handleValidationResult(BindException exception) {
    	StringBuilder builder = new StringBuilder();
    	for (ObjectError error : exception.getAllErrors()) {
    		builder.append("," + StringUtils.arrayToDelimitedString(error.getCodes(), ","))
				   .append(":").append(error.getDefaultMessage());
    	}

    	return R.error(builder.toString().replace(",", ""));
    }


    @ExceptionHandler({Exception.class})
    public Object handleException(Exception e, HttpServletRequest request) {
        LogDO logDO = new LogDO();
        logDO.setGmtCreate(new Date());
        logDO.setOperation(Constant.LOG_ERROR);
        logDO.setMethod(request.getRequestURL().toString());
        logDO.setParams(e.toString());
        UserDO current = ShiroUtils.getUser();
        if (null!=current) {
            logDO.setUserId(current.getUserId());
            logDO.setUsername(current.getUsername());
        }

        logService.save(logDO);
        logger.error(e.getMessage(), e);
        if (HttpServletUtils.jsAjax(request)) {
            return R.error(500, "服务器错误，请联系管理员");
        }
        return new ModelAndView("error/500");
    }
}
